package com.orangelife.mobile.parkingcard.activity;

/**
 * 申请停车卡---初始
 */

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ReplacementTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.sp.CommSp2;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.view.NewConfirmDialog;
import com.orangelife.mobile.common.view.OneBtnConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.parkingcard.bean.ParkingInfomation;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class ApplyForParkingCardBeginActivity extends OrangeLifeBaseActivity {

    /**
     * 有停车位服务的时候显示的界面
     */
    private LinearLayout llHaveParking;
    /**
     * 没有停车位服务的时候显示的界面
     */
    private LinearLayout llNoneParking;
    /**
     * 没有停车位服务的时候显示的文字提示
     */
    private TextView tvNoParkingToast;
    /**
     * 选择小区
     */
    private LinearLayout llCommunity;
    /**
     * 选择房屋楼栋号
     */
    private LinearLayout llBuilding;
    /**
     * 姓名
     */
    private EditText etName;
    /**
     * 车牌号
     */
    private EditText etCarNumber;
    /**
     * 停车场类型
     */
    private LinearLayout llParkingType;
    /**
     * 房号
     */
    private LinearLayout llRoom;
    /**
     * 缴费激活
     */
    private Button btnPayActive;

    /**
     * 停车类型
     */
    private TextView tvParkingType;
    /**
     * 房屋楼栋
     */
    private TextView tvBuilding;
    /**
     * 小区
     */
    private TextView tvCommunity;
    /**
     * 标题
     */
    private TextView tvTitle;
    /**
     * 提示信息
     */
    private TextView tvTips;
    /**
     * 房号
     */
    private TextView tvRoom;
    /**
     * 小区ID
     */
    private String commID = "";
    /**
     * 楼栋ID
     */
    private String buildingID = "";
    /**
     * 房间号ID
     */
    private String apartmentID = "";
    /**
     * 停车场终端ID
     */
    private String parkID = "";
    /**
     * 第三方停车卡ID
     */
    private String carsID = "";
    /**
     * 停车服务是否开通 0未开通；1开通
     */
    private String park;
    private Dialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_card_begin);
        initeView();
        findView();
    }

    /**
     * 初始化
     */
    private void initeView() {
        llHaveParking = (LinearLayout) findViewById(R.id.llHaveParking);
        llNoneParking = (LinearLayout) findViewById(R.id.llNoneParking);
        tvNoParkingToast = (TextView) findViewById(R.id.tvNoParkingToast);
        llCommunity = (LinearLayout) findViewById(R.id.llCommunity);
        llBuilding = (LinearLayout) findViewById(R.id.llBuilding);
        llRoom = (LinearLayout) findViewById(R.id.llRoom);
        etName = (EditText) findViewById(R.id.etName);
        etCarNumber = (EditText) findViewById(R.id.etCarNumber);
        llParkingType = (LinearLayout) findViewById(R.id.llParkingType);
        btnPayActive = (Button) findViewById(R.id.btnPayActive);
        tvBuilding = (TextView) findViewById(R.id.tvBuilding);
        tvCommunity = (TextView) findViewById(R.id.tvCommunity);
        tvParkingType = (TextView) findViewById(R.id.tvParkingType);
        tvRoom = (TextView) findViewById(R.id.tvRoom);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTips = (TextView) findViewById(R.id.tvTips);
        // 判断显示哪一个界面
        parkingCheck();
    }

    /**
     * 赋值
     */
    private void findView() {
        tvCommunity.setText(CommSp2.getCommName());
        tvTitle.setText("添加停车卡");
        tvNoParkingToast.setText("“" + CommSp2.getCommName() + "”" + getResources().getString(R.string.no_parking_place));
        etCarNumber.setTransformationMethod(new InputLowerToUpper());
        llBuilding.setOnClickListener(listener);
        llParkingType.setOnClickListener(listener);
        llRoom.setOnClickListener(listener);
        btnPayActive.setOnClickListener(listener);
    }

    /**
     * 点击监听器
     */
    public OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.llCommunity:
                    startActivityForResult(new Intent(ApplyForParkingCardBeginActivity.this,
                            CommunityActivity.class), 100);
                    break;
                case R.id.llBuilding:
                    if (StringUtil.isBlank(tvCommunity.getText().toString())) {
                        ToastHelper.getInstance()._toast("请先选择小区");
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("commID", commID);
                        intent.setClass(ApplyForParkingCardBeginActivity.this,
                                BuildingActivity.class);
                        startActivityForResult(intent, 200);
                    }
                    break;
                case R.id.llRoom:
                    if (StringUtil.isBlank(tvBuilding.getText().toString())) {
                        ToastHelper.getInstance()._toast("请先选择楼栋号");
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("buildingID", buildingID);
                        intent.setClass(ApplyForParkingCardBeginActivity.this,
                                RoomActivity.class);
                        startActivityForResult(intent, 400);
                    }
                    break;
                case R.id.llParkingType:
                    if (StringUtil.isBlank(tvCommunity.getText().toString())) {
                        ToastHelper.getInstance()._toast("请先选择小区");
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("commID", commID);
                        intent.setClass(ApplyForParkingCardBeginActivity.this,
                                ParkingTypeActivity.class);
                        startActivityForResult(intent, 300);
                    }
                    break;
                case R.id.btnPayActive:
                    if (StringUtil.isBlank(tvCommunity.getText().toString())
                            || StringUtil.isBlank(tvBuilding.getText().toString())
                            || StringUtil.isBlank(tvRoom.getText().toString())) {
                        ToastHelper.getInstance()._toast(getResources().getString(R.string.community_building_toast));
                    } else if (StringUtil.isBlank(etName.getText().toString())
                            || StringUtil.isBlank(etCarNumber.getText().toString())
                            || !StringUtil.isPlate_(etCarNumber.getText().toString().trim())) {
                        ToastHelper.getInstance()._toast(getResources().getString(R.string.name_carnumber_toast));
                    } else if (StringUtil.isBlank(tvParkingType.getText().toString())) {
                        ToastHelper.getInstance()._toast(getResources().getString(R.string.parkingtype_toast));
                    } else {
                        //提交申请
                        upToApply();
                    }
                    break;

                default:
                    break;
            }
        }
    };

    public class InputLowerToUpper extends ReplacementTransformationMethod {
        @Override
        protected char[] getOriginal() {
            char[] lower = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
            return lower;
        }

        @Override
        protected char[] getReplacement() {
            char[] upper = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            return upper;
        }

    }

//    public void showDialog() {
//        String message = etCarNumber.getText().toString() + "已被绑定，请检查车牌号后重试。如有疑问，请联系小区物业";
//        final OneBtnConfirmDialog confirmDialog = new OneBtnConfirmDialog(
//                ApplyForParkingCardBeginActivity.this, getResources().getString(R.string.warm_prompt),
//                message, getResources().getString(
//                R.string.sure));
//        confirmDialog.show();
//        confirmDialog
//                .setClicklistener(new OneBtnConfirmDialog.ClickListenerInterface() {
//
//                    @Override
//                    public void doConfirm() {
//                        confirmDialog.dismiss();
//                    }
//                });
//    }

    public void showDialog() {
        String message = etCarNumber.getText().toString() + "已被绑定，请检查车牌号后重试。如有疑问，请联系小区物业";
        final NewConfirmDialog confirmDialog = new NewConfirmDialog(
                ApplyForParkingCardBeginActivity.this, getResources().getString(R.string.warm_prompt),
                message, getResources().getString(
                R.string.sure));
        confirmDialog.show();
        confirmDialog
                .setClicklistener(new NewConfirmDialog.ClickListenerInterface() {
                    @Override
                    public void doLeft() {

                    }

                    @Override
                    public void doRight() {
                        confirmDialog.dismiss();
                    }
                });
    }

    /**
     * 看看该小区是否开通了停车位服务
     */
    private void parkingCheck() {
        dialog = DialogHelper.getInstance().createLoadingDialog(ApplyForParkingCardBeginActivity.this, getResources().getString(R.string.loading_data_please_wait));
        dialog.show();
        commID = CommSp2.getCommID();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("commID", commID);
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", map);
        rootMap.put("url", Constant.WHETHER_OPENING_PARKING);
        rootMap.put("wat", 1);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    /***
     * 激活
     */
    @SuppressWarnings("deprecation")
    private void upToApply() {
        getDataFromServer();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("apartmentID", apartmentID);
        map.put("parkID", parkID);
        map.put("name", etName.getText().toString());
        map.put("house", tvBuilding.getText().toString() + tvRoom.getText().toString());
        map.put("plate", StringUtil.tranUpperCase(etCarNumber.getText().toString()));
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", map);
        rootMap.put("url", Constant.URL_ADD_PARKING_CARD);
        rootMap.put("wat", 0);
        new JSONRequest(JSONRequest.POST, rootMap, handler, HttpUtil.ACTION_JSON);
    }

    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this, Constant.LOADING);
        dialog.show();
    }

    /**
     * 处理获得的数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Map<String, Object> map = JSONHelper.jsonToMap(msg.obj.toString());
                    String errInfo = map.get("errInfo").toString();
                    if (errInfo.equals("OK")) {
                        ToastHelper.getInstance()._toast("激活成功");
                        Map<String, Object> mapEntity = (Map<String, Object>) map.get("entity");
                        carsID = mapEntity.get("cardsID").toString();
                        ParkingInfomation.setCommunity(tvCommunity.getText().toString(), ApplyForParkingCardBeginActivity.this);
                        ParkingInfomation.setBuilding(tvBuilding.getText().toString(), ApplyForParkingCardBeginActivity.this);
                        ParkingInfomation.setRoom(tvRoom.getText().toString(), ApplyForParkingCardBeginActivity.this);
                        ParkingInfomation.setName(etName.getText().toString(), ApplyForParkingCardBeginActivity.this);
                        ParkingInfomation.setCommID(commID, ApplyForParkingCardBeginActivity.this);
                        ParkingInfomation.setApartmentID(apartmentID, ApplyForParkingCardBeginActivity.this);
                        jumpToFeeActivity();
                    }
                    break;
                case 1:
                    HashMap<String, Object> map1 = (HashMap<String, Object>) JSONHelper
                            .jsonToMap(String.valueOf(msg.obj));
                    String errInfo1 = map1.get("errInfo").toString();
                    if (errInfo1.equals("OK")) {
                        dialog.dismiss();
                        HashMap<String, Object> map2 = (HashMap<String, Object>) map1
                                .get("entity");
                        park = String.valueOf(map2.get("park"));
                        if (park.equals("0")) {
                            llHaveParking.setVisibility(View.GONE);
                            llNoneParking.setVisibility(View.VISIBLE);
                        } else {
                            llHaveParking.setVisibility(View.VISIBLE);
                            llNoneParking.setVisibility(View.GONE);
                        }
                    }

                    break;
                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog);
                case 1003:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case 66002:
                    showDialog();
                    break;
                default:
                    break;
            }
            DialogHelper.closeDialog(dialog);
        }

    };


    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            if (resultCode == 1000) {
                Bundle bundle = data.getExtras();
                Map<String, Object> map = (Map<String, Object>) bundle.get("map");
                tvCommunity.setText(map.get("comm").toString());
                tvBuilding.setText("");
                tvRoom.setText("");
                tvParkingType.setText("");
                commID = map.get("comID").toString();
            }
        }
        if (requestCode == 200) {
            if (resultCode == 2000) {
                Bundle bundle = data.getExtras();
                Map<String, Object> map = (Map<String, Object>) bundle.get("map");
                tvBuilding.setText(map.get("buildingName").toString());
                tvRoom.setText("");
                buildingID = map.get("buildingID").toString();
            }
        }
        if (requestCode == 300) {
            if (resultCode == 3000) {
                Bundle bundle = data.getExtras();
                Map<String, Object> map = (Map<String, Object>) bundle.get("map");
                tvParkingType.setText(map.get("parkingName").toString());
                parkID = map.get("parkID").toString();
            }
        }
        if (requestCode == 400) {
            if (resultCode == 4000) {
                Bundle bundle = data.getExtras();
                Map<String, Object> map = (Map<String, Object>) bundle.get("map");
                tvRoom.setText(map.get("apartmentName").toString());
                apartmentID = map.get("apartmentID").toString();
            }
        }
    }

    /**
     * 提交申请后跳转到停车卡缴费页面
     */
    private void jumpToFeeActivity() {
        Bundle bundle = new Bundle();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("carNumber", StringUtil.tranUpperCase(etCarNumber.getText().toString()));
        map.put("parkingType", tvParkingType.getText().toString());
        map.put("cardsID", carsID);
        map.put("parkID", parkID);
        IntentHelper.getInstances().bundleWithExtra(ApplyForParkingCardBeginActivity.this, ParkingCardFeeActivity.class, bundle, (Serializable) map);
        finish();
    }
}
